package com.example.demotype;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.List;

/**
 * @author: 迟家鑫
 * @date: 2021/1/16 18:34
 * @description:
 */
public class WildcardTypeTest {

    private List<? extends Number> listNum;
    private List<? super String> listStr;

    public static void main(String[] args) throws Exception {
        // ? 通配符表达式，表示通配符泛型，但是WildcardType并不属于Java-Type中的一种；例如：List<？extend Number>
        // 和 List<? super Integer>;
        Field listNum = WildcardTypeTest.class.getDeclaredField("listStr");
        Type genericType = listNum.getGenericType();
        System.out.println("Type Name : " + genericType);
        System.out.println("Class Name : " + genericType.getClass().getName());
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        for (Type actualTypeArgument : actualTypeArguments) {
            System.out.println(actualTypeArgument);
            System.out.println(actualTypeArgument.getClass());
            WildcardType wildcardType = (WildcardType) actualTypeArgument;
            // 1 getUpperBounds 获取泛型变量的上边界（extends）
            Type[] upperBounds = wildcardType.getUpperBounds();
            System.out.println("upper start ...");
            for (Type upperBound : upperBounds) {
                System.out.println(upperBound);
            }
            System.out.println("upper end ...");
            System.out.println("lower end ...");
            // 2 getLowerBounds 获取泛型变量的下边界
            Type[] lowerBounds = wildcardType.getLowerBounds();
            for (Type lowerBound : lowerBounds) {
                System.out.println(lowerBound);
            }
            System.out.println("lower end ...");
        }


    }
}
